<template>
    <div class="multip-input-wrapper">
        <el-input
            v-model="inputValue"
            class="multip-input"
            :class="{ 'is-focused': isFocused }"
            :placeholder="placeholder"
            @change="handleInputChange"
            @focus="isFocused = true"
            @blur="isFocused = false">
            <template #prefix>
                <div class="tags-wrapper">
                    <el-tag
                        v-if="firstTag"
                        class="tag-item"
                        size="small"
                        type="success"
                        effect="light"
                        closable
                        @close="handleFirstTagClose">
                        {{ firstTag }}
                    </el-tag>
                    <el-popover
                        v-if="tags.length > 1"
                        placement="bottom"
                        :width="200"
                        trigger="click"
                        popper-class="tags-popover">
                        <template #reference>
                            <el-tag
                                class="tag-count"
                                size="small"
                                type="warning"
                                effect="light">
                                +{{ tags.length - 1 }}
                            </el-tag>
                        </template>
                        <div class="tags-list">
                            <div 
                                v-for="(tag, index) in tags.slice(1)" 
                                :key="index"
                                class="tag-item">
                                {{ tag }}
                            </div>
                        </div>
                    </el-popover>
                </div>
            </template>
            <template #suffix>
                <el-popover
                    v-model:visible="popoverVisible"
                    trigger="click"
                    :width="popoverWidth"
                    popper-class="multip-input-popover"
                    @show="handlePopoverShow">
                    <div class="popover-content" ref="popoverRef">
                        <!-- <div class="popover-header">
                            <span class="title">批量编辑</span>
                            <el-icon class="close-icon" @click="handleCancel">
                                <Close />
                            </el-icon>
                        </div> -->
                        <div class="popover-body">
                            <el-input
                                v-model="textareaValue"
                                type="textarea"
                                :rows="textareaRows"
                                :placeholder="textareaPlaceholder"
                                resize="none"
                                class="popover-textarea"
                                @input="handleTextareaInput"
                                @keydown.enter.prevent="handleSubmit"
                                @keydown.esc="handleCancel" />
                        </div>
                        <div class="popover-actions">
                            <el-button 
                                size="small" 
                                @click="handleReset" 
                                :disabled="!textareaValue">
                                清除
                            </el-button>
                            <el-button
                                size="small"
                                type="primary"
                                @click="handleSubmit"
                                :disabled="!textareaValue">
                                确定
                            </el-button>
                        </div>
                    </div>
                    <template #reference>
                        <div
                            class="edit-icon"
                            ref="iconRef"
                            :class="{ 'is-active': popoverVisible }"
                            @click.stop>
                            <el-icon size="large">
                                <Edit />
                            </el-icon>
                        </div>
                    </template>
                </el-popover>
            </template>
        </el-input>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import { Edit, Close } from '@element-plus/icons-vue';
import { ElInput, ElPopover, ElButton, ElIcon, ElTag } from 'element-plus';
import type { MultipInputProps, MultipInputEmits } from './types';

// 注册 Element Plus 组件
defineOptions({
    name: 'MultipInput',
    components: {
        ElInput,
        ElPopover,
        ElButton,
        ElIcon,
        ElTag
    }
});

// Props 定义
const props = withDefaults(defineProps<MultipInputProps>(), {
    modelValue: '',
    placeholder: '请输入',
    popoverWidth: 450,
    textareaRows: 8,
    textareaPlaceholder: '请输入多行文本，每行一个值'
});

// Emits 定义
const emit = defineEmits<MultipInputEmits>();

// 响应式状态
const inputValue = computed({
    get: () => '',
    set: (val) => {
        const formattedValue = formatInputValue(val);
        emit('update:modelValue', formattedValue);
        emit('change', formattedValue);
    }
});

const textareaValue = ref('');
const popoverVisible = ref(false);
const isFocused = ref(false);
const popoverRef = ref<HTMLElement>();
const iconRef = ref<HTMLElement>();

// 计算属性
const tags = computed(() => {
    if (!props.modelValue) return [];
    const value = String(props.modelValue);
    return value.split(',').filter(Boolean);
});

const firstTag = computed(() => {
    return tags.value[0] || '';
});

// 方法
const handleInputChange = (val: string) => {
    const formattedValue = formatInputValue(val);
    emit('update:modelValue', formattedValue);
    emit('change', formattedValue);
};

const handleTextareaInput = (val: string) => {
    textareaValue.value = val.replace(/[ ]/g, '');
};

const handlePopoverShow = () => {
    textareaValue.value = props.modelValue.replace(/,/g, '\n');
};

const handleReset = () => {
    textareaValue.value = '';
};

const handleSubmit = () => {
    if (!textareaValue.value) return;
    
    const formattedValue = formatTextareaValue(textareaValue.value);
    emit('update:modelValue', formattedValue);
    emit('change', formattedValue);
    popoverVisible.value = false;
};

const handleCancel = () => {
    popoverVisible.value = false;
};

const handleFirstTagClose = () => {
    const newTags = [...tags.value];
    newTags.shift();
    const formattedValue = newTags.join(',');
    emit('update:modelValue', formattedValue);
    emit('change', formattedValue);
};

const formatInputValue = (val: string): string => {
    return val
        .replace(/[ ]/g, '')
        .replace(/，/g, ',')
        .replace(/[,]{2,}/g, ',')
        .replace(/^,|,$/g, '');
};

const formatTextareaValue = (val: string): string => {
    return val
        .split(/[\r\n]+/)
        .map(line => line.trim())
        .filter(Boolean)
        .join(',');
};

// 点击外部关闭
const handleClickOutside = (event: MouseEvent) => {
    if (!popoverRef.value?.contains(event.target as Node) && 
        !iconRef.value?.contains(event.target as Node)) {
        popoverVisible.value = false;
    }
};

// 生命周期
onMounted(() => {
    document.addEventListener('click', handleClickOutside);
});

onBeforeUnmount(() => {
    document.removeEventListener('click', handleClickOutside);
});
</script>

<style lang="less" scoped>
.multip-input-wrapper {
    .multip-input {
        &.is-focused {
            .edit-icon {
                color: var(--el-color-primary);
            }
        }

        :deep(.el-input__inner) {
            padding-left: 0;
        }
    }

    .edit-icon {
        display: flex;
        align-items: center;
        cursor: pointer;
        transition: color 0.3s;
        
        &:hover {
            color: var(--el-color-primary);
        }
        
        &.is-active {
            color: var(--el-color-primary);
        }
    }

    .tags-wrapper {
        display: flex;
        align-items: center;
        gap: 4px;
        margin-right: 4px;
        
        .tag-item {
            max-width: 120px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            border-radius: 4px;
            
            :deep(.el-tag__close) {
                margin-left: 4px;
            }
        }
        
        .tag-count {
            border-radius: 4px;
            cursor: pointer;
        }
    }
}

:deep(.tags-popover) {
    .tags-list {
        max-height: 200px;
        overflow-y: auto;
        
        .tag-item {
            padding: 8px 12px;
            font-size: 13px;
            color: var(--el-text-color-regular);
            border-bottom: 1px solid var(--el-border-color-lighter);
            
            &:last-child {
                border-bottom: none;
            }
            
            &:hover {
                background-color: var(--el-fill-color-light);
            }
        }
    }
}

    .popover-content {
        padding: 0;
        position: relative;
        display: flex;
        flex-direction: column;
        height: 100%;
        
        .popover-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 12px 16px;
            border-bottom: 1px solid var(--el-border-color-lighter);
            
            .title {
                font-size: 14px;
                font-weight: 500;
                color: var(--el-text-color-primary);
            }
            
            .close-icon {
                cursor: pointer;
                font-size: 16px;
                color: var(--el-text-color-secondary);
                
                &:hover {
                    color: var(--el-text-color-primary);
                }
            }
        }
        
        .popover-body {
            flex: 1;
            overflow: hidden;
            padding: 16px;
            
            .popover-textarea {
                height: 100%;
                
                :deep(.el-textarea__inner) {
                    font-family: monospace;
                    line-height: 1.5;
                    height: 100%;
                    resize: none;
                }
            }
        }
        
        .popover-actions {
            display: flex;
            justify-content: flex-end;
            gap: 8px;
            padding: 0 16px;
            border-top: 1px solid var(--el-border-color-lighter);
            background-color: var(--el-fill-color-blank);
        }
    
}
</style>
